package com.cocostudio.erpapp.utils;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import com.cocostudio.erpapp.MainActivity;
import com.cocostudio.erpapp.common.Debug;
import com.cocostudio.erpapp.vo.ErpDeptment;
import com.cocostudio.erpapp.vo.LoginResult;
import com.cocostudio.erpapp.vo.ScheduleList;
import com.cocostudio.erpapp.vo.ValueObject;
import com.cocostudio.erpapp.vo.WSHistorySaleResult;
import com.cocostudio.erpapp.vo.WSLoginResult;
import com.cocostudio.erpapp.vo.WSRealTimeSalesResult;
import com.cocostudio.erpapp.vo.WSRealtimeStockResult;
import com.cocostudio.erpapp.web.Apis;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import android.util.Log;
import android.widget.Toast;

public class WebServiceUtils {

    public static final String LOCALSTORE = "LocalStore";
    private static final String TAG = "WebService";

    //  private static String [] deptlist=null;

    private static ArrayList<ErpDeptment> deptlist = null;

    public static WSLoginResult loginsession = null;

    // Webservice服务器地址  
    public static String SERVER_URL = "http://erp.uvhc.cn/WebServer.asmx?WSDL";

    public static String SERVER_IP;
    //调用的webservice命令空间  
    public static String NAME_SPACE = "http://www.uvhc.cn/";
    //用户登录 
    private static final String M_LOGIN = "Login";

    //实时销售查询
    private static final String M_REALTIME_SALES = "RealtimeSale";

    //读取实时库存
    private static final String M_REALTIME_STORE = "RealtimeStock";

    //查询历史销售
    private static final String M_HISTORY_SALE = "HistorySale";

    //部门历史销售
    private static final String M_DEPT_HISTORY_SALE = "DeptHistorySale";

    //单品查询
    private static final String M_GET_GOODS_INFO = "GetGoodsInfo";

    //实时收款方式
    private static final String M_REALTIME_PAYMENTS = "RealtimePayments";


    private static final int SO_TIMEOUT = 5000;
    private static final int CONNECTION_TIMEOUT = 5000;

    private static final String header_userid = "hello";

    private static final String header_password = "world";

    private static Element[] soap_header = null;

    private static boolean DEBUG = true;

    static {

        soap_header = new Element[1];
        soap_header[0] = new Element().createElement(NAME_SPACE, "MySoapHeader");

        Element UserId = new Element().createElement(NAME_SPACE, "UserId");
        UserId.addChild(Node.TEXT, header_userid);
        soap_header[0].addChild(Node.ELEMENT, UserId);

        Element Password = new Element().createElement(NAME_SPACE, "Password");
        Password.addChild(Node.TEXT, header_password);
        soap_header[0].addChild(Node.ELEMENT, Password);
    }

    public static ArrayList<ErpDeptment> buildDeptList(int level) {
        ArrayList<ErpDeptment> list = new ArrayList<ErpDeptment>();

        if (deptlist == null)
            return null;

        if (deptlist.size() == 0)
            return null;

        for (ErpDeptment item : deptlist) {

            if (item.getName().trim().equals(""))
                continue;
            if (item.getCode().length() == (level * 2)) {
                list.add(new ErpDeptment(item.getName(), item.getCode(), "", level));
            }
        }


        return list;
    }


    public static String buildParam(Map param) {

        if (MainActivity.curlogin != null)
            param.put("personCode", MainActivity.curlogin.getPersonCode());

        StringBuffer sb = new StringBuffer(100);
        sb.append("{");
        int index = 1;
        for (Iterator iterator = param.keySet().iterator(); iterator.hasNext(); ) {
            String type = (String) iterator.next();
            sb.append("\"" + type + "\"");
            sb.append(":");
            sb.append("\"" + param.get(type).toString() + "\"");
            if (index < param.size()) {
                sb.append(",");
            }
            index++;
        }
        sb.append("}");

        return sb.toString();
    }

    public static String WSInvoke(final String method, String request) {

        String result = null;
        SoapObject soapobject = new SoapObject(NAME_SPACE, method);
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
        soapobject.addProperty("request", request);
        if (DEBUG)
            System.out.println("method:" + method + " request:" + request);
        envelope.headerOut = soap_header;
        envelope.bodyOut = soapobject;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(soapobject);
        System.out.println("请求地址:" + SERVER_URL);
        final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);
        httpSE.debug = true;

        FutureTask<String> future = new FutureTask<String>(
                new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        String result = null;
                        httpSE.call(null, envelope);
                        if (envelope.getResponse() != null) {
                            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                            result = response.toString();
                            if (DEBUG)
                                System.out.println("method:" + method + " response:" + response);
                        }
                        return result;
                    }
                });

        new Thread(future).start();
        try {
            result = future.get();

            if (!validatecheck(result))
                result = "{Result:0,Message:\"数据返回格式有误\"}";
        } catch (InterruptedException e) {
            e.printStackTrace();
            JsonObject err = new JsonObject();
            err.addProperty("Result", 0);
            err.addProperty("Message", "请求被中断");
            result = err.toString();
        } catch (ExecutionException e) {
            e.printStackTrace();
            result = "{Result:0,Message:\"数据请求未响应\"}";
        }

        return result;
    }

    public static boolean validatecheck(String result) {
        boolean rtn = false;
        if (result.endsWith("}")) {
            rtn = true;
        }
        return rtn;
    }


    //{"PersonName":"张三","DeptList":[{"DeptId":"0102030405","DeptName":"末级部门"},{"DeptId":"02","DeptName":"一级部门"}],"Result":"1","Message":""}
    public static WSLoginResult WS_Login(String username, String password) {

        WSLoginResult result = null;
        String request = "";

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("personcode", username);
        param.put("password", password);
        request = buildParam(param);

        String ws_result = WSInvoke(M_LOGIN, request);
        // ws_result =" {\"PersonName\":\"张三\",\"DeptList\":[{\"DeptId\":\"010203\",\"DeptName\":\"末级部门\"},{\"DeptId\":\"02\",\"DeptName\":\"一级部门\"}],\"Result\":\"1\",\"Message\":\"\"}";
        if (ws_result != null) {
            result = new Gson().fromJson(ws_result, WSLoginResult.class);
        }
        return result;
    }

    public static void setDeptResult(WSLoginResult result) {

        WebServiceUtils.deptlist = new ArrayList<ErpDeptment>();
        ArrayList<HashMap<String, String>> dplist = result.getDeptList();
        for (HashMap<String, String> item : dplist) {
            WebServiceUtils.deptlist.add(new ErpDeptment(item.get("DeptName"), item.get("DeptId"), "", item.get("DeptId").toString().length() / 2));
        }
    }

    public static boolean checkHasDeptLevel(int level) {
        if (WebServiceUtils.deptlist == null) return false;
        boolean rtn = false;

        for (ErpDeptment item : WebServiceUtils.deptlist) {
            if (item.getLevel() == level) {
                rtn = true;
                return rtn;
            }
        }
        return rtn;
    }


    public static String WS_RealTimeStock_json(
            String deptid,
            String deptlevel,
            String catalog,
            String goodsCode,
            String goodsBarcode,
            String showtype
    ) {
        String result = "";
        String request = "";

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("deptid", deptid);
        param.put("deptLevel", deptlevel);
        param.put("catalog", catalog);

        if (!StringUtil.isEmpty(goodsCode))
            param.put("goodsCode", goodsCode);
        else if (!StringUtil.isEmpty(goodsBarcode))
            param.put("goodsCode", goodsBarcode);
        else
            param.put("goodsCode", "");


        param.put("OrderBy", "1");
        param.put("showtype", showtype);

        if (showtype.equals("4"))
            param.put("personCode", MainActivity.curlogin.getPersonCode());

        request = buildParam(param);
        result = WSInvoke(M_REALTIME_STORE, request);
        return result;
    }

    public static String WS_RealTimeSales_json(
            String deptid,
            String deptlevel,
            String catalog,
            String goodsCode,
            String goodsBarcode,
            String showtype
    ) {
        String result = "";
        String request = "";

        HashMap<String, String> param = new HashMap<String, String>();
        param.put("deptid", deptid);
        param.put("deptLevel", deptlevel);
        param.put("catalog", catalog);
        if (!StringUtil.isEmpty(goodsCode))
            param.put("goodsCode", goodsCode);
        else if (!StringUtil.isEmpty(goodsBarcode))
            param.put("goodsCode", goodsBarcode);
        else
            param.put("goodsCode", "");


        param.put("OrderBy", "1");
        param.put("showtype", showtype);
        request = buildParam(param);
        result = WSInvoke(M_REALTIME_SALES, request);
        return result;
    }


    public static String WS_GetGoodsInfo_json(
            String goodscode,
            String goodsBarcode,
            String goodsname,
            String goodsspec,
            String showtype) {
        String result = "";
        String request = "";
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("showtype", showtype);

        if (!StringUtil.isEmpty(goodscode))
            param.put("goodsCode", goodscode);
        else if (!StringUtil.isEmpty(goodsBarcode))
            param.put("goodsCode", goodsBarcode);
        else
            param.put("goodsCode", "");
        param.put("orderBy", "1");
        param.put("goodsname", goodsname);
        param.put("goodsspec", goodsspec);
        request = buildParam(param);
        result = WSInvoke(M_GET_GOODS_INFO, request);
        return result;
    }


    public static String WS_RealtimePayments_json() {
        String result = "";
        String request = "";
        HashMap<String, String> param = new HashMap<String, String>();
        request = buildParam(param);

        result = WSInvoke(M_REALTIME_PAYMENTS, request);

        return result;

    }


    //{"startdate":"2011-12-01","enddate":"2011-12-31","deptid":"01","showtype":"1","deptLevel":"10"}
    public static String WS_DeptHistorySale_json(
            String startdate,
            String enddate,
            String deptid,
            String deptlevel,
            String showtype
    ) {
        String result = "";
        String request = "";
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("deptid", deptid);
        param.put("startdate", startdate);
        param.put("deptLevel", deptlevel);
        param.put("startend", enddate);
        param.put("showtype", showtype);
        request = buildParam(param);

        result = WSInvoke(M_DEPT_HISTORY_SALE, request);

        return result;

    }


    public static String WS_HistorySale_json(
            String deptid,
            String deptLevel,
            String catalog,
            String goodsCode,
            String goodsBarcode,
            String startDate,
            String endDate,
            String showtype
    ) {
        String result = "";
        String request = "";
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("deptid", deptid);
        param.put("deptLevel", deptLevel);
        param.put("catalog", catalog);
        if (!StringUtil.isEmpty(goodsCode))
            param.put("goodsCode", goodsCode);
        else if (!StringUtil.isEmpty(goodsBarcode))
            param.put("goodsCode", goodsBarcode);
        else
            param.put("goodsCode", "");


        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("OrderBy", "1");
        param.put("showtype", showtype);
        request = buildParam(param);

        result = WSInvoke(M_HISTORY_SALE, request);
        return result;
    }

    public static ArrayList<HashMap<String, String>> WS_ServerList() {
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

        return list;
    }


}
